<!-- 随访用户 -->
<template>
  <globalModal :width="1000" title="日程安排" :visible="visible" @cancel="handleCancel">
    <a-tabs v-model="scheduleId" @change="changeTab">
      <a-tab-pane key="1" tab="新增" v-if="isCanAdd"> </a-tab-pane>
      <a-tab-pane :tab="`日程${index + 1}`" v-for="(item, index) in scheduleList" :key="item.scheduleId"></a-tab-pane>
    </a-tabs>
    <a-spin :spinning="confirmLoading">
      <a-form :form="form" autocomplete="off" @submit="handleOk" :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }">
        <a-form-item label="所属医院" v-if="isAdmin" :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }">
          <a-input
            placeholder="请选择所属医院"
            v-decorator="[
              'deptId',
              {
                rules: [{ required: true, message: '请选择所属医院' }],
              },
            ]"
            readOnly
            style="display: none"
          />
          <span class="ant-input-group-wrapper">
            <span class="ant-input-wrapper ant-input-group">
              <input
                v-model="deptName"
                :disabled="!(isCanAdd && hasEdit(scheduleId))"
                placeholder="请选择所属医院"
                type="text"
                readonly="true"
                class="ant-input"
              />
              <span
                class="ant-input-group-addon"
                v-if="isCanAdd && hasEdit(scheduleId)"
              ><a-icon
                @click="changeDept"
                slot="addonAfter"
                type="setting"
                style="cursor: pointer"
              /></span>
            </span>
          </span>
        </a-form-item>
        <a-row :gutter="16">
          <a-col :span="24">
            <a-form-item label="安排医生">
              <a-input
                placeholder="请选择安排医生"
                v-decorator="[
                  'doctorIds',
                  {
                    rules: [{ required: true, message: '请选择安排医生' }],
                  },
                ]"
                readOnly
                style="display: none"
              />

              <span class="ant-input-group-wrapper">
                <span class="ant-input-wrapper ant-input-group">
                  <input v-if="!doctorList || doctorList.length == 0" placeholder="请选择安排医生" type="text" readonly="true" class="ant-input" />
                  <div class="ant-input" v-else style="padding: 4px 5px; height: auto">
                    <a-tag @close="delDoctor(item)" :closable="doctorList.length > 1 && isCanAdd" v-for="(item, index) in doctorList" :key="item.doctorId">
                      {{ item.realName }}
                    </a-tag>
                  </div>
                  <span
                    class="ant-input-group-addon"
                    v-if="isCanAdd && hasEdit(scheduleId)"
                  ><a-icon
                    @click="changeDoctor"
                    slot="addonAfter"
                    type="setting"
                    style="cursor: pointer"
                  /></span>
                </span>
              </span>
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="24">
            <a-form-item label="时间" :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }">
              <a-date-picker
                format="YYYY-MM-DD"
                placeholder="时间"
                style="width: 100%"
                :disabledDate="disabledDate"
                :disabled="!(isCanAdd && hasEdit(scheduleId))"
                v-decorator="['schedDate', { rules: [{ required: true, message: '请选择时间' }] }]"
              />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="24">
            <a-form-item label="工作内容" :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }">
              <a-textarea
                :rows="3"
                placeholder="请输入"
                autocomplete="off"
                :disabled="!(isCanAdd && hasEdit(scheduleId))"
                v-decorator="['remark', { rules: [{ required: true, message: '请输入工作内容' }] }]"
              />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-spin>
    <template slot="footer">
      <div class="my-modal-footer" v-if="isCanAdd && hasEdit(scheduleId)">
        <a-button type="danger" @click="del" v-if="scheduleId != 1">删除</a-button>
        <a-button class="ant-btn-cancel" @click="handleCancel">取消</a-button>
        <a-button type="primary" class="ant-btn-ok" @click="handleOk">确定</a-button>
      </div>
      <div v-else></div>
    </template>
    <change-dept-modal ref="changeDeptModal" @selectDept="selectDept"></change-dept-modal>
    <select-doctor-modal ref="selectDoctorModal" @selectDoctor="selectDoctor"></select-doctor-modal>
  </globalModal>
</template>

<script>
import { doctorManageapi } from "@/api/index.js";
import { ModalMixins } from "@/mixins";
import changeDeptModal from "@/components/changeDeptModal.vue";
import selectDoctorModal from "./selectDoctorModal.vue";
import moment from "moment";
import { mapState } from "vuex";
export default {
  name: "AddScheduleModal",
  mixins: [ModalMixins],
  components: {
    changeDeptModal,
    selectDoctorModal
  },
  computed: {
    ...mapState({
      userInfo: (state) => state.user.userinfo || {}
    })
  },
  data () {
    return {
      doctorList: [],
      deptName: "",
      deptId: "",
      doctorName: "",
      scheduleId: "1",
      scheduleList: [],
      day: "",
      isCanAdd: false
    };
  },
  created () {},
  methods: {
    show (day, list) {
      this.day = day;
      this.isCanAdd = moment().isBefore(day) || moment().format("YYYY-MM-DD") == moment(day).format("YYYY-MM-DD");
      if (this.isCanAdd) {
        this.scheduleId = "1";
      } else {
        this.scheduleId = list[0].scheduleId;
        this.$nextTick(() => {
          this.changeTab(this.scheduleId);
        });
      }

      this.visible = true;
      this.scheduleList = [...list];
      this.$nextTick(() => {
        this.form.setFieldsValue({
          schedDate: day
        });
      });
    },
    changeTab (key) {
      console.log("key", key);
      if (key == 1) {
        this.deptName = "";
        this.doctorName = "";
        this.form.setFieldsValue({
          schedDate: this.day,
          deptId: "",
          doctorIds: "",
          remark: ""
        });
        this.doctorList = [];
      } else {
        const info = this.scheduleList.find((item) => item.scheduleId == key);
        console.log("数据" + JSON.stringify(info));
        this.deptName = info.deptName;
        this.doctorName = info.doctorName;
        this.deptId = info.deptId;
        const param = {
          schedDate: this.day,
          deptId: info.deptId,
          // doctorIds: info.doctorIds,
          doctorIds: info.doctorVos.map((item) => item.doctorId).join(","),
          remark: info.remark
        };
        this.doctorList = info.doctorVos.map((item) => {
          return {
            doctorId: item.doctorId,
            realName: item.doctorName,
            phone: item.doctorPhone
          };
        });
        if (this.isAdmin) {
          param.deptId = info.deptId;
        }
        this.$nextTick(() => {
          this.form.setFieldsValue(param);
        });
      }
    },
    del () {
      this.$postAction(doctorManageapi.scheduleUrl.delete, [this.scheduleId]).then((res) => {
        if (res && res.code == 1) {
          this.$message.success("删除成功");
          this.$emit("ok");
          // const index = this.scheduleList.findIndex((item) => item.scheduleId == this.scheduleId);
          this.scheduleList = this.scheduleList.filter((item) => item.scheduleId != this.scheduleId);
          this.scheduleId = "1";
          this.changeTab(1);
        }
      });
    },
    disabledDate (current) {
      // 不能选择今天之前的日期（包括今天）
      // return current && current < moment().endOf('day');

      // 如果只想禁止今天之前的（不包括今天）：
      return current && current < moment().startOf("day");
    },
    handleCancel () {
      this.visible = false;
      this.doctorList = [];
      this.deptName = "";
      this.deptId = "";
      this.doctorName = "";
      this.$emit("close");
    },
    resetForm () {
      this.doctorList = [];
      this.deptName = "";
      this.deptId = "";
      this.doctorName = "";
    },
    handleOk () {
      this.form.validateFields((err, values) => {
        // 验证表单没错误
        if (!err) {
          console.log("val", values);
          const parameter = Object.assign(
            {
              orgId: this.globalOrgId
            },
            values,
            this.scheduleId != "1"
              ? {
                scheduleId: this.scheduleId
              }
              : ""
          );
          if (parameter.schedDate) {
            parameter.schedDate = parameter.schedDate.format("YYYY-MM-DD") + " 00:00:00";
          }
          if (parameter.doctorIds) {
            parameter.doctorIds = parameter.doctorIds.split(",");
          }
          this.confirmLoading = true;
          this.$postAction(this.scheduleId == "1" ? doctorManageapi.scheduleUrl.add : doctorManageapi.scheduleUrl.edit, parameter)
            .then((res) => {
              if (res && res.code == 1) {
                this.$message.success("保存成功");
                this.$emit("ok", this.isAdd);
                this.form.resetFields();
                this.resetForm();
                // this.handleCancel();
              }
            })
            .finally(() => {
              this.confirmLoading = false;
            });
        }
      });
    },
    changeDept (value) {
      if (this.isAdmin && !this.globalOrgId) {
        this.$message.error("请先选择一个机构");
        return false;
      }
      this.$refs.changeDeptModal.show(this.globalOrgId);
    },
    selectDept (dept) {
      this.deptName = dept.deptName;
      this.deptId = dept.deptId;
      this.doctorList = [];
      this.$nextTick(() => {
        this.form.setFieldsValue({
          deptId: dept.deptId,
          doctorIds: ""
        });
      });
    },
    selectDoctor (doctorList) {
      console.log("doctorList", doctorList);
      this.doctorList = [...doctorList];
      this.$nextTick(() => {
        this.form.setFieldsValue({
          doctorIds: this.doctorList.map((item) => item.doctorId).join(",")
        });
      });
    },
    changeDoctor () {
      if (!this.deptId && this.isAdmin) {
        this.$message.error("请选择所属医院");
        return;
      }
      // const selectDoctorIds = this.doctorList.map((item) => item.doctorId);
      this.$refs.selectDoctorModal.show(this.deptId, this.doctorList);
      /* this.$refs.selectDoctorModal.show(this.deptId, selectDoctorIds); */
    },
    hasEdit () {
      // console.log("this.scheduleId", this.scheduleId);
      if (!this.isAdmin && this.scheduleId != 1) {
        const info = this.scheduleList.find((item) => item.scheduleId == this.scheduleId);
        console.log("info", info, this.scheduleId);
        return info.createBy == this.userInfo.username;
      }
      return true;
    },
    delDoctor (info) {
      this.doctorList = this.doctorList.filter((item) => item.doctorId != info.doctorId);
      this.$nextTick(() => {
        this.form.setFieldsValue({
          doctorIds: this.doctorList.map((item) => item.doctorId).join(",")
        });
      });
    }
  }
};
</script>

<style lang="less" scoped></style>
